<template>
  <div class="score-container">
    <span class="title">
      {{ currentView === "all" ? "各科目测试统计" : "测试详情" }}
    </span>
    <div v-show="flag" ref="chartRef" class="chart-container"></div>
    <div v-show="!flag" class="empty-container">
      <van-empty description="暂无数据">
        <van-button 
          size="small" 
          type="primary" 
          @click="handleButtonClick"
          icon="arrow-left"
          class="query-btn"
        >返回</van-button>
      </van-empty>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, nextTick } from "vue";
import selfTestResult from "@/api/selfTest/selfTestResult";
import * as echarts from "echarts";

const flag = ref(true);

const handleButtonClick = async () => {
  currentView.value = "all";
  initChart();
};

// 声明图表实例的引用
let myCharts = null;
// 添加变量跟踪当前显示的是哪种数据
const currentView = ref("all");
const currentSubjectId = ref(null);

const chartRef = ref(null);

// 修改初始化图表的函数
const initChart = async () => {
  if (!chartRef.value) return;
  
  if (!myCharts) {
    myCharts = echarts.init(chartRef.value);
  } else {
    myCharts.clear();
    myCharts.off("click");
  }

  let res;
  let option;

  if (currentView.value === "all") {
    // 显示所有科目的统计
    res = await selfTestResult.allStatistics();
    flag.value = res.data.data.length > 0;

    option = {
      legend: {
        data: ["测试次数", "平均得分"],
        top: 10,
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      xAxis: {
        data: res.data.xaxis,
        axisLabel: {
          rotate: 45,
          formatter: function (value) {
            return value.length > 5 ? "..." + value.slice(-5) : value;
          },
        },
      },
      yAxis: [
        {
          type: 'value',
          name: '测试次数',
          position: 'left',
        },
        {
          type: 'value',
          name: '平均得分',
          position: 'right',
          max: 100,
          min: 0,
        }
      ],
      series: [
        {
          name: "测试次数",
          type: "bar",
          data: res.data.data.map((value, index) => ({
            value: value,
            id: res.data.ids[index],
          })),
          label: {
            show: true,
            position: "top",
          },
          emphasis: {
            focus: "series",
          },
          itemStyle: {
            color: "#91cc75",
          },
          barGap: "30%",
          yAxisIndex: 0,
        },
        {
          name: "平均得分",
          type: "bar",
          data: res.data.data2.map((value, index) => ({
            value: value,
            id: res.data.ids[index],
          })),
          label: {
            show: true,
            position: "top",
          },
          emphasis: {
            focus: "series",
          },
          itemStyle: {
            color: "#ee6666",
          },
          yAxisIndex: 1,
        },
      ],
      grid: {
        top: "15%",
        left: "3%",
        right: "8%",
        bottom: "15%",
        containLabel: true,
      },
    };

    // 为全局视图添加点击事件
    myCharts.on("click", function (params) {
      if (params.componentType === "series" && params.seriesType === "bar") {
        currentSubjectId.value = params.data.id;
        currentView.value = "subject";
        initChart();
      }
    });
  } else {
    // 显示单个科目的详细统计
    res = await selfTestResult.statisticsBySubject(currentSubjectId.value);
    flag.value = res.data.data.length > 0;

    option = {
      legend: {
        data: ["测试次数", "平均得分"],
        top: 10,
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      xAxis: {
        data: res.data.xaxis,
        axisLabel: {
          rotate: 45,
          formatter: function (value) {
            return value.length > 5 ? "..." + value.slice(-5) : value;
          },
        },
      },
      yAxis: [
        {
          type: 'value',
          name: '测试次数',
          position: 'left',
        },
        {
          type: 'value',
          name: '平均得分',
          position: 'right',
          max: 100,
          min: 0,
        }
      ],
      series: [
        {
          name: "测试次数",
          type: "bar",
          data: res.data.data.map((value, index) => ({
            value: value,
            id: res.data.ids[index],
          })),
          label: {
            show: true,
            position: "top",
          },
          emphasis: {
            focus: "series",
          },
          itemStyle: {
            color: "#91cc75",
          },
          barGap: "30%",
          yAxisIndex: 0,
        },
        {
          name: "平均得分",
          type: "bar",
          data: res.data.data2.map((value, index) => ({
            value: value,
            id: res.data.ids[index],
          })),
          label: {
            show: true,
            position: "top",
          },
          emphasis: {
            focus: "series",
          },
          itemStyle: {
            color: "#ee6666",
          },
          yAxisIndex: 1,
        },
      ],
      grid: {
        top: "15%",
        left: "3%",
        right: "8%",
        bottom: "15%",
        containLabel: true,
      },
    };

    // 为详情视图添加返回功能
    myCharts.on("click", function () {
      currentView.value = "all";
      initChart();
    });
  }

  if (flag.value) {
    myCharts.setOption(option);
  }
};

onMounted(() => {
  nextTick(() => {
    initChart();
    window.addEventListener('resize', () => {
      myCharts?.resize();
    });
  });
});

onUnmounted(() => {
  if (myCharts) {
    window.removeEventListener('resize', () => {
      myCharts?.resize();
    });
    myCharts.dispose();
    myCharts = null;
  }
});
</script>

<style scoped>
.score-container {
  background-color: white;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px;
}

.title {
  margin: 5px 0;
}

.chart-container {
  flex: 1;
  min-height: 300px;
}

.empty-container {
  height: 300px;
}
</style>
